<template>
    <div class="about">
        <h1>mounted 计算属性</h1>
        <fieldset>
            <legend>计算属性</legend>
            <div>
                <p>aaa: <input type="text" v-model="aaa" /></p>
                <p>
                    <input type="text" v-model="user.name" />
                </p>
                <p>{{ fun_name(user.name) }}</p>
                <input type="text" v-model="fun_name_2" />
            </div>
        </fieldset>
        <!-- <button @click="watch1">watch1</button> -->
        <!-- <button @click="watch2">watch2</button> -->
				<button @click="stopWatch2">取消 watch2 监听</button>
    </div>
</template>
<script>
import { defineComponent, ref, computed, watch, watchEffect } from 'vue';
export default defineComponent({
	setup(){
		let aaa = ref(1111)
		let user = ref({
			name: '你大爷',
			job: '前端'
		})

		let fun_name =  computed(()=>{
			return (e)=>{
				console.log('computed', '我是: ' + e );
				return '我是: ' + e
			}
		})

		let fun_name_2 =  computed({
			get(){
				return user.value.name + '_' + user.value.job
			},
			// 姓名_工作框里修改姓名时给前一个姓名赋值，val：get中返回的值
			set(val){
				user.value.name = val.split('_')[0]
			}
		})
		
		function watch1(){
			// 监听非响应的数据时，需要加上 ()=>xxx
			// watch([aaa, user], ([ new_aaa, new_user ], [ aaa, user ])=>{
			// () => user.value.name
			watch([ aaa, user, (()=>user.value.name) ], ([ aaa, user, name ])=>{
				console.log('watch1', aaa, user, name );
			}, {
				immediate: true,		// 初次进入就监听
				deep: true,				// 深度监听
			})
		}

		let watch2;
		function wacthFun() {
			watch2 = watch([ aaa, user, ()=>user.value.name ], ([ aaa, user, name ])=>{
				console.log('watch2', aaa, user, name, 222 );
			}, {
				immediate: true,		// 初次进入就监听, 默认false
				deep: true,				// 深度监听
			})
		}
		wacthFun()

		function stopWatch2() {
			console.log('watch2 监听取消，5s 后重新开启')
			watch2()
			setTimeout(() => {
				wacthFun()
			}, 5000);
		}
		
		// 监听，默认初次执行，不需要 immediate: true
		watchEffect(()=>{
			// console.log('watchEffect', aaa.value, user.value);
		},{
			immediate: true,
			deep: true
		})
		watchEffect()

		return {
			aaa,
			user,
			fun_name,
			fun_name_2,
			stopWatch2
		}
	}
});
</script>
